#!/bin/sh

WDIR=`dirname $0`
cd "${WDIR}/.."
MAINDIR=`pwd -P`
LIGHTTPD_CONF="$MAINDIR/lp/lighttpd.conf"
PIDFILE="$MAINDIR/tmp/run/lighttpd.pid"
PIDFILE2="$MAINDIR/tmp/run/lp.pid"
SOCKET="$MAINDIR/tmp/run/fcgi.socket"
export PYTHONPATH="$MAINDIR"

okerror() {
    R=$1
    if [[ $R == 0 ]]; then
        echo "[ ok ]"
    else
        echo "[ !! ]"
    fi
}

case "$1" in
    "start")
        echo "Starting django fastcgi" | tr "\n" "\t\t\t"
        lp/manage.py runfcgi socket="$SOCKET" workdir="$MAINDIR/lp" pidfile="$PIDFILE2" daemonize=true &> /dev/null
        okerror $?
        echo "Starting Lighttpd" | tr "\n" "\t\t\t"
        /usr/sbin/lighttpd -f "$LIGHTTPD_CONF" &> /dev/null
        okerror $?
    ;;
    "stop")
        echo "Stopping Lighttpd" | tr "\n" "\t\t\t"
        kill `cat $PIDFILE 2> /dev/null` &> /dev/null
        okerror $?
        echo "Stopping django fastcgi" | tr "\n" "\t\t\t"
        kill `cat $PIDFILE2 2> /dev/null` &> /dev/null
        okerror $?
        rm -f -- "$PIDFILE2" "$SOCKET" &> /dev/null
    ;;
    *)
        echo "Usage: $0 (start|stop)"
        exit 1
    ;;
esac
